package com.cloudkinto.service.user.captchamode.impl;

import com.cloudkinto.common.common.CodeGenerator;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.entity.UserDo;
import com.cloudkinto.service.email.MailSenderService;
import com.cloudkinto.service.user.captchamode.CaptchaModeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @author zhangyy
 * @date 2020/10/15 10:58
 * @description:
 */
public class MailSendMsgImpl implements CaptchaModeService {
    private UserDo userDo;

    private RedisTemplate redisTemplate;

    private MailSenderService mailSenderService;

    public MailSendMsgImpl(UserDo userDo, RedisTemplate redisTemplate, MailSenderService mailSenderService) {
        this.userDo = userDo;
        this.redisTemplate = redisTemplate;
        this.mailSenderService = mailSenderService;
    }

    @Override
    public void sendMsg(int type) {
        if (StringUtils.isBlank(userDo.getUserMail())) {
            throw new BizException("该账号未绑定邮箱，无法通过邮箱验证");
        }
        String generate4Number = CodeGenerator.generate4Number();
        try {
            if (type == SysConstant.DELETE_FLAG_FALSE) {
                mailSenderService.sendEmail("【cloudkinto】验证码", "您的验证码为:【" + generate4Number + "】用于登录验证，打死不要告诉别人哦！", userDo.getUserMail());
            } else {
                mailSenderService.sendEmail("【cloudkinto】验证码", "您的验证码为:【" + generate4Number + "】用于找回密码，打死不要告诉别人哦！", userDo.getUserMail());
            }
        } catch (Exception e) {
            throw new BizException("验证码发送失败，原因可能是：当前账号没有绑定邮箱，或绑定的邮箱错误");
        }
        redisTemplate.opsForValue().set("phoneCode:" + userDo.getUserAccount(), generate4Number, 5, TimeUnit.MINUTES);
    }
}
